package com.secsbrain.development.web.controller;

import com.secsbrain.cmdb.client.iface.AppInfoService;
import com.secsbrain.common.EnumDefinition;
import com.secsbrain.common.ErrorCodeEnum;
import com.secsbrain.common.ResponseResult;
import com.secsbrain.common.utils.DateTimeUtils;
import com.secsbrain.development.biz.IDeployApprovalService;
import com.secsbrain.development.biz.exception.BizMessageException;
import com.secsbrain.development.dal.model.DeployApproval;
import com.secsbrain.development.remote.SsoRemoteService;
import com.secsbrain.development.web.utils.BranchUtils;
import com.secsbrain.sso.model.dto.system.UserDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import com.secsbrain.common.ResponseVo;
import com.secsbrain.cmdb.client.model.AppDetail;
import com.secsbrain.development.web.dto.ActivityRecord;
import com.secsbrain.development.web.dto.ApproveDeployDTO;
import com.secsbrain.development.web.dto.SingleTaskDTO;
import com.secsbrain.engine.client.iface.TaskInfoService;
import com.secsbrain.engine.client.model.HistoryTask;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

/**
 * 构建审核控制层
 *
 * @author zhaoyi
 */
@RequestMapping("api/buildApproval")
@RestController
@ApiIgnore
public class BuilderApprovalController {
	
    private static final Logger LOGGER = LoggerFactory.getLogger(BuilderApprovalController.class);
    
    @Autowired
    IDeployApprovalService deployApprovalService;
    
    @Autowired
	SsoRemoteService userServiceFacade;
    
	@Autowired
	AppInfoService appInfoService;
	
	@Autowired
	TaskInfoService taskInfoService;
    
    /**
     * 功能描述: <br>
     * 单实例/灰度发布申请
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/singletonApply", method = RequestMethod.POST)
    public ResponseResult singletonApply(@Valid @RequestBody SingleTaskDTO param) {
		DeployApproval deployApproval=new DeployApproval();
		deployApproval.setAppId(param.getAppId());
		deployApproval.setBranch(param.getGitBranch());
		deployApproval.setEnv(param.getEnv());
		deployApproval.setGroupName(param.getGroupName());

		String checkResult= BranchUtils.checkBranchName(param.getEnv(),param.getGitBranch());
		if(StringUtils.isNotEmpty(checkResult)){
			throw new BizMessageException(checkResult);
		}
		
		deployApprovalService.singleDeployApproval(deployApproval);
     	return new ResponseResult<>();
    }
    
    /**
     * 功能描述: <br>
     * 全量发布申请
     *
     * @param groupId
	 * @param envName
     * @return
     */
    @RequestMapping(value = "/groupBApply", method = RequestMethod.POST)
    public ResponseResult groupBApply(Long groupId,String envName) {
		deployApprovalService.groupBApproval(groupId, envName);
		return new ResponseResult<>();
    }


    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
    public ResponseResult info(@PathVariable("id") long id) {
    	DeployApproval deployApproval=deployApprovalService.selectById(id);
        if (deployApproval != null) {
			ResponseVo<AppDetail> appVo=appInfoService.queryAppDetailById(deployApproval.getAppId());
        	deployApproval.setAppName(appVo.getData().getName());
        	deployApproval.setCreateTimeStr(DateTimeUtils.parseDateAsString(deployApproval.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
			return new ResponseResult<>(deployApproval);
        } else {
			return new ResponseResult<>(ErrorCodeEnum.ERROR_COMMON_SYSTEM.getCode(),"无效的发布审批ID");
        }
    }
    
    @RequestMapping(value = "/approveNew", method = RequestMethod.POST)
    public ResponseResult approve(@RequestBody ApproveDeployDTO approveProjectDTO) {
        if(!approveProjectDTO.getPass()){
        	Assert.hasText(approveProjectDTO.getComment(), "驳回备注不能为空");
        }
        deployApprovalService.approve(approveProjectDTO);
		return new ResponseResult<>();
	}
    
    /**
     * 功能描述: <br>
     * 查看活动记录
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryActivity/{id}", method = RequestMethod.GET)
	public ResponseResult queryActivity(@PathVariable("id") long id){
    	try{
			DeployApproval deployApproval=deployApprovalService.selectById(id);

			ResponseVo<List<HistoryTask>> taskResult=taskInfoService.historyByInstanceId(deployApproval.getProcessInstanceId());
			List<ActivityRecord> activityRecordList=new ArrayList<ActivityRecord>();
			if(taskResult.isSuccess()){
				List<HistoryTask> historyTaskList=taskResult.getData();
				for(HistoryTask historyTask:historyTaskList){
					if("Exclusive Gateway".equals(historyTask.getActivityName())){
						continue;
					}

					ActivityRecord activityRecord=new ActivityRecord();
					activityRecord.setActivityName(historyTask.getActivityName());
					activityRecord.setAssignee(historyTask.getAssignee());
					if(historyTask.getEndTime()!=null){
						activityRecord.setEndTime(DateTimeUtils.dateParseString((historyTask.getEndTime())));
					}
					if(historyTask.getStartTime()!=null) {
						activityRecord.setStartTime(DateTimeUtils.dateParseString(historyTask.getStartTime()));
					}

					if(historyTask.getAssignee()!=null){
						ResponseResult<UserDTO> userResult=userServiceFacade.getUserDTO(Long.parseLong(historyTask.getAssignee()));
						if(userResult.getCode() == EnumDefinition.CommonStatus.YES.getCode()){
							activityRecord.setAssignee(userResult.getData().getRealname());
						}else{
							LOGGER.error("调用获取用户信息接口失败："+userResult.getMsg());
						}
					}

					if(historyTask.getEndTime()!=null){
						activityRecord.setStatus("已处理");
					}else{
						activityRecord.setStatus("待处理");
					}
					activityRecordList.add(activityRecord);
				}
			}
			return new ResponseResult<>(activityRecordList);
		}catch (Exception e){
			LOGGER.error("",e);
			return ResponseResult.getFailedResult(ErrorCodeEnum.ERROR_COMMON_SYSTEM);
		}

    }
    
}
